package com.easyj.base.security.filter;



import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import com.easyj.base.common.ajax.Result;
import com.easyj.base.security.SecurityConstant;
import com.easyj.base.security.service.JCacheSecurityService;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码登陆过滤器
 */

@Component
public class CaptchaCodeFilter extends OncePerRequestFilter {
    private static final PathMatcher pathMatcher = new AntPathMatcher();
    
    @Autowired 
	private  JCacheSecurityService securityService;
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if(isAuthUrl(request)) {
        	try {
	            String paramCode = request.getParameter("code");
	            String uuid = request.getParameter("uuid");
	            if(StringUtils.isBlank(paramCode)||StringUtils.isBlank(uuid)) {
	            	 throw new Exception("验证码错误！"); 
	            }
	            
	            String sessionCode =securityService.getCaptchaCode(uuid);
	            if(sessionCode==null) {
	            	throw new Exception("验证码过期！"); 
	            }

	            if(paramCode.equalsIgnoreCase(sessionCode)) { // 不分区大小写
	            	filterChain.doFilter(request,response);
	               
	            }else {
	            	throw new Exception("验证码错误！");
	            }
        	}catch(Exception ex) {
        		// ex.printStackTrace();
        		 ObjectMapper objectMapper=new ObjectMapper();
            	 Result R=Result.Error(ex.getMessage());
         		 String json = objectMapper.writeValueAsString(R);
         	     response.setContentType("application/json;charset=UTF-8");
         	     response.getWriter().write(json);
        	}
        } else {
            filterChain.doFilter(request,response);
        }
    }

   

    /**
        * 拦截登陆请求
     */
    private boolean isAuthUrl(HttpServletRequest request) {
        return "POST".equals(request.getMethod()) &&
                pathMatcher.match(SecurityConstant.Auth_LOGIN_URL, request.getServletPath());
    }
}
